package com.wwc.bwcj.fragment

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wwc.bwcj.R
import com.wwc.bwcj.adapter.CartAdapter
import com.wwc.bwcj.entity.CartProduct
import com.wwc.bwcj.entity.OrderItem
import com.wwc.bwcj.util.CartManager
import com.wwc.bwcj.util.OnCartChangeListener
import com.wwc.bwcj.util.OrderManager

/**
 * 购物车页面
 */
class CartFragment : Fragment(), OnCartChangeListener {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: CartAdapter
    private val cartItems = ArrayList<CartProduct>()
    private var totalTextView: TextView? = null
    private var checkoutButton: Button? = null // 添加下单按钮引用

    // 加载布局
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_cart, container, false)
    }

    // 初始化组件和适配器
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView = view.findViewById(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(context)
        adapter = CartAdapter(cartItems, this)
        recyclerView.adapter = adapter
        totalTextView = view.findViewById(R.id.tv_total)
        checkoutButton = view.findViewById(R.id.btn_checkout) // 初始化下单按钮

        // 设置下单按钮点击事件
        checkoutButton?.setOnClickListener {
            checkout()
        }

        // 加载购物车数据
        loadCartItems()
    }

    // 加载购物车数据
    private fun loadCartItems() {
        cartItems.clear()
        // 通过 CartManager.getCartItems() 获取购物车中的所有商品
        cartItems.addAll(CartManager.getCartItems())
        // 将数据传递给 CartAdapter ,CartAdapter 负责在 RecyclerView 中展示商品列表
        adapter.notifyDataSetChanged()
        updateTotalAmount()
    }

    // 更新总价，当监听到购物车数据变化时，总价会得到重新计算，达到刷新的效果
    private fun updateTotalAmount() {
        totalTextView?.text = "总计: ¥${String.format("%.2f", adapter.getTotalAmount())}"
    }

    // 实现 OnCartChangeListener 接口,购物车数据变化时更新总金额显示
    override fun onCartChanged() {
        updateTotalAmount()
    }

    // 结算方法
    private fun checkout() {
        // 检查购物车是否为空
        if (cartItems.isEmpty()) {
            showEmptyCartDialog()
            return
        }

        // 创建订单信息
        val orderTitle = buildOrderTitle()
        val orderTime = getCurrentTime()
        val totalPrice = adapter.getTotalAmount()

        // 获取第一个商品的图片资源
        val firstProductImage = if (cartItems.isNotEmpty()) {
            getProductImageByName(cartItems[0].productName)
        } else {
            R.drawable.product_byjx // 默认图片
        }

        // 创建订单项
        val orderItem = OrderItem(
            id = generateOrderId(),
            title = orderTitle,
            orderTime = orderTime,
            totalPrice = totalPrice,
            productImage = firstProductImage,
            status = "已完成"
        )

        // 保存订单
        OrderManager.addOrder(orderItem)

        // 显示成功提示
        showOrderSuccessDialog()

        // 清空购物车
        clearCart()
    }

    // 构建订单标题
    private fun buildOrderTitle(): String {
        val itemCount = cartItems.size
        val items = cartItems.map { it.productName }.joinToString(", ")
        return "$items 共${itemCount}件商品"
    }

    // 获取当前时间
    private fun getCurrentTime(): String {
        val now = java.util.Date()
        val formatter = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
        return formatter.format(now)
    }

    // 生成订单ID
    private fun generateOrderId(): String {
        return "order_${System.currentTimeMillis()}"
    }

    // 根据商品名称获取对应的图片资源
    private fun getProductImageByName(productName: String): Int {
        return when (productName) {
            "伯牙绝弦" -> R.drawable.product_byjx
            "栀香柠" -> R.drawable.product_zxn
            "琥珀光" -> R.drawable.product_hpg
            "白雾红尘" -> R.drawable.product_bwhc
            "桂馥兰香" -> R.drawable.product_gflx
            "山野栀子" -> R.drawable.product_syzz
            "花田乌龙" -> R.drawable.product_htwl
            "万里木兰" -> R.drawable.product_wlml
            else -> R.drawable.product_byjx // 默认图片
        }
    }

    // 显示空购物车提示
    private fun showEmptyCartDialog() {
        activity?.let {
            AlertDialog.Builder(it)
                .setTitle("购物车为空")
                .setMessage("您的购物车中没有商品，请先添加商品再结算。")
                .setPositiveButton("确定") { dialog, _ ->
                    dialog.dismiss()
                }
                .show()
        }
    }

    // 显示下单成功提示框
    private fun showOrderSuccessDialog() {
        activity?.let {
            AlertDialog.Builder(it)
                .setTitle("下单成功")
                .setMessage("您的订单已成功提交！")
                .setPositiveButton("确定") { dialog, _ ->
                    dialog.dismiss()
                }
                .setCancelable(false)
                .show()
        }
    }

    // 清空购物车
    private fun clearCart() {
        cartItems.clear()
        adapter.notifyDataSetChanged()
        updateTotalAmount()
        CartManager.clearCart()
    }
}
